#include <parse.h>
#include <QDebug>
#include <QtXml> 

#include <QContactModel>
#include <gcontact.h>



QMap<QString,QString>  parseContacts(
    const QString & xml,
    const QMap<QString,QString> groupmap
    ) 
{

  qDebug() << "contacts parser called";

  QMap<QString,QString> idmap;
  
  QDomDocument doc;
  doc.setContent(xml, true);

  QDomElement element = doc.documentElement();
  QContactModel filter;

  for(QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling()) {

    // address
    if (n.nodeName() == "entry") {

    
      GoogleContact contact;
      bool update = false;

      for(QDomNode nn = n.firstChild(); !nn.isNull(); nn = nn.nextSibling()) {
        QDomElement ee = nn.toElement();

        // parsing 
        QString tag  = ee.tagName();
        QString text = ee.text();

        if (tag == "title" ) {
          qDebug() << "\nend\n======\n";

          qDebug() << text <<":\n";

          if (text.isEmpty()) 
            break;

          filter.setFilter(text);

          qDebug() << "found" << filter.count();
          if ( filter.count() == 1) {
            QContact c = filter.contact(0);

            contact = GoogleContact( c );
            contact.google(n,groupmap);
            update = true;
            qDebug() << "single match" << contact.label() << contact.uid().toString();

          } else if (filter.count() == 0) {
            contact = GoogleContact(n,groupmap);
            contact.setFirstName( text );
            qDebug() << "creating new contact for " << text;
          } else {
            // FIXME
            
            qDebug() << "multi match";

            for (int i =0; i < filter.count(); ++i) {
              QContact match = filter.contact(i);
              qDebug() << "match: " << match.label();

            }

          }
        }         
        
      }


      if (contact.label().isEmpty()) {
          qDebug() << "skipping empty";
          continue;
      }

      if (update)
        filter.updateContact(contact); 
      else
        filter.addContact(contact);

    }

  }
  return idmap;

}

QMap<QString,QString>  parseGroups(const QString & xml) {
  qDebug() << "groups parser called";
  QMap<QString,QString> map;
  
  QDomDocument doc;
  doc.setContent(xml, true);

  QDomElement element = doc.documentElement();

  for(QDomNode n = element.firstChild(); !n.isNull(); n = n.nextSibling()) {

    if (n.nodeName() == "entry") {

      QString id;


      for(QDomNode nn = n.firstChild(); !nn.isNull(); nn = nn.nextSibling()) {
        QDomElement ee = nn.toElement();

        // parsing 
        QString tag  = ee.tagName();
        QString text = ee.text();

        if (tag == "id") 
          id = text;
         else if (tag == "title") 
          map[id] = text;
        

        
      }
    }
  }

  return map;

}


